<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Language" content="zh-cn">
    
    
    <title>
        
            排序 | Nefelibata
             | Nefelibata
        
    </title>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    
        <meta name="theme-color" content="#77AAFF">
    
    
    <meta name="keywords" content="">
    
    

    

    <!-- Baidu Push -->
<script>
	(function(){
		var bp = document.createElement('script');
		var curProtocol = window.location.protocol.split(':')[0];
		if (curProtocol === 'https') {
			bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
		}
		else {
			bp.src = 'http://push.zhanzhang.baidu.com/push.js';
		}
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(bp, s);
	})();

	var _hmt = _hmt || [];
</script>



    
    <meta name="description" content="排序">
<meta property="og:type" content="article">
<meta property="og:title" content="排序">
<meta property="og:url" content="https://nefelibata.icu/2022/10a444b428.html">
<meta property="og:site_name" content="Nefelibata">
<meta property="og:description" content="排序">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picture-0111.oss-cn-beijing.aliyuncs.com/img/20221015114004.png">
<meta property="article:published_time" content="2022-10-15T03:08:40.000Z">
<meta property="article:modified_time" content="2024-01-04T02:41:48.350Z">
<meta property="article:author" content="Nefelibata">
<meta property="article:tag" content="Simple">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picture-0111.oss-cn-beijing.aliyuncs.com/img/20221015114004.png">
    
        <link rel="alternate" type="application/atom+xml" title="Nefelibata" href="/blog/atom.xml">
    
    <link rel="shortcut icon" href="/blog/img/favicon.ico">
    <link id="style" rel="stylesheet" href="/blog/css/style.css?v=3.0">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    
<meta name="generator" content="Hexo 6.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>

<body>
    <div id="loading" class="active"></div>
    <aside id="menu"  class >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" >
      <div class="brand">
        <a class="avatar waves-effect waves-circle waves-light">
          <img src="/blog/img/avatar.jpg" alt="avatar">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname" id="name">Nefelibata</h5>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
              <li class="waves-block waves-effect">
                  <a href="/blog/" target="_self" >
                    <i class="icon icon-lg icon-home"></i>
                    <span>主 页</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/archives" target="_self" >
                    <i class="icon icon-lg icon-archives"></i>
                    <span>归 档</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/categories" target="_self" >
                    <i class="icon icon-lg icon-th-list"></i>
                    <span>分 类</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/tags" target="_self" >
                    <i class="icon icon-lg icon-tags"></i>
                    <span>标 签</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/../gallery" target="_blank" >
                    <i class="icon icon-lg icon-image"></i>
                    <span>相册</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/../about" target="_blank" >
                    <i class="icon icon-lg icon-smile-o"></i>
                    <span>关 于</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
              <li class="waves-block waves-effect">
                  <a href="/blog/../" target="_self" >
                    <i class="icon icon-lg icon-tree"></i>
                    <span>Nefelibata</span><i class="icon icon-lg icon-caret-left"></i>
                  </a>
              </li>
            
      <div class="nav2">
          
              <a class="nav2item" data-title="Email" href="mailto:kunpengl0111@gamil.com" target="_parent"title="Email" >
                <i class="icon icon-lg icon-envelope-o envelope-o"></i>
              </a>
          
              <a class="nav2item" data-title="Github" href="https://github.com/kpl0111" target="_blank"title="Github" >
                <i class="icon icon-lg icon-github github"></i>
              </a>
          
              <a class="nav2item" data-title="Twitter" href="https://twitter.com/Nefelib31847846" target="_blank"title="Twitter" >
                <i class="icon icon-lg icon-twitter twitter"></i>
              </a>
          
        </div>
      </ul>
    </div>
  </div>
</aside>


    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">排序</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        <a href="../../atom.xml" target="_blank" class="header-icon waves-effect waves-circle waves-light" id="Rss">
            <i class="icon icon-lg icon-rss"></i>
        </a>
    </div>
</header>
<header class="content-header post-header">
    <div class="container fade-scale">
        <div id="myheader">
            <h1 class="title">
                
            </h1>
            <h5 class="subtitle">
                
                
            </h5>
        </div>
    </div>
</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            
                <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F%EF%BC%88Bubble-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89%EF%BC%88%E8%B6%85%E5%87%BA%E6%97%B6%E9%97%B4%E9%99%90%E5%88%B6%EF%BC%89"><span class="post-toc-text">冒泡排序（Bubble Sort）（稳定排序）（超出时间限制）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F%EF%BC%88Select-Sort%EF%BC%89%EF%BC%88%E9%9D%9E%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89%EF%BC%88%E8%B6%85%E5%87%BA%E6%97%B6%E9%97%B4%E9%99%90%E5%88%B6%EF%BC%89"><span class="post-toc-text">选择排序（Select Sort）（非稳定排序）（超出时间限制）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E6%8F%92%E5%85%A5%E6%8E%92%E5%BA%8F%EF%BC%88Insect-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89%EF%BC%88%E8%B6%85%E5%87%BA%E6%97%B6%E9%97%B4%E9%99%90%E5%88%B6%EF%BC%89"><span class="post-toc-text">插入排序（Insect Sort）（稳定排序）（超出时间限制）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F%EF%BC%88Shell-Sort%EF%BC%89%EF%BC%88%E9%9D%9E%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">希尔排序（Shell Sort）（非稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F%EF%BC%88Merge-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">归并排序（Merge Sort）（稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%EF%BC%88Quick-Sort%EF%BC%89%EF%BC%88%E9%9D%9E%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">快速排序（Quick Sort）（非稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%A0%86%E6%8E%92%E5%BA%8F%EF%BC%88Heap-Sort%EF%BC%89%EF%BC%88%E9%9D%9E%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">堆排序（Heap Sort）（非稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E8%AE%A1%E6%95%B0%E6%8E%92%E5%BA%8F%EF%BC%88Count-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">计数排序（Count Sort）（稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E6%A1%B6%E6%8E%92%E5%BA%8F%EF%BC%88Bucket-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">桶排序（Bucket Sort）（稳定排序）</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#%E5%9F%BA%E6%95%B0%E6%8E%92%E5%BA%8F%EF%BC%88Radix-Sort%EF%BC%89%EF%BC%88%E7%A8%B3%E5%AE%9A%E6%8E%92%E5%BA%8F%EF%BC%89"><span class="post-toc-text">基数排序（Radix Sort）（稳定排序）</span></a></li></ol>
            
        </nav>
    </aside>
   
<article id="post-排序"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">排序</h1>
        <div class="post-meta">
            <i class="icon icon-lg icon-calendar-o"></i>
            发表于
            <time class="post-time" title="2022-10-15 11:08:40" datetime="2022-10-15T03:08:40.000Z"  itemprop="datePublished">2022-10-15</time>

            <br id="mybreak"/>
            
	<i class="icon icon-lg icon-folder-o"></i>
	分类：<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/blog/categories/%E7%83%82%E7%AC%94%E5%A4%B4/">烂笔头</a></li></ul>


            <i>·</i>
        </div>
        <div class="post-count-custom">
            <i class="icon icon-lg icon-comment-o"></i>
            阅读本文可能花费您&nbsp;<span class="post-count">16.1</span>&nbsp;分钟
        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>排序</p>
<span id="more"></span>

<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://picture-0111.oss-cn-beijing.aliyuncs.com/img/20221015114004.png" alt="20221015114004" title="">
                </div>
                <div class="image-caption">20221015114004</div>
            </figure>

<h2 id="冒泡排序（Bubble-Sort）（稳定排序）（超出时间限制）"><a href="#冒泡排序（Bubble-Sort）（稳定排序）（超出时间限制）" class="headerlink" title="冒泡排序（Bubble Sort）（稳定排序）（超出时间限制）"></a>冒泡排序（Bubble Sort）（稳定排序）（超出时间限制）</h2><p>比较相邻元素，如果第一个比第二个大，则交换。</p>
<p>时间复杂度$n^2$，空间复杂度1</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // bubbleSort
        int n = nums.size();
        for (int i = 0; i &lt; n - 1; ++i) {
            bool flag = false;
            for (int j = 0; j &lt; n - 1 - i; ++j) {
                if (nums[j] &gt; nums[j + 1]) {
                    swap(nums[j], nums[j + 1]);
                    flag = true;
                }                 
            }
            if (flag == false) break; //无交换，代表当前序列已经最优 
        }
        return nums;
    }
};
</code></pre>
<h2 id="选择排序（Select-Sort）（非稳定排序）（超出时间限制）"><a href="#选择排序（Select-Sort）（非稳定排序）（超出时间限制）" class="headerlink" title="选择排序（Select Sort）（非稳定排序）（超出时间限制）"></a>选择排序（Select Sort）（非稳定排序）（超出时间限制）</h2><p>依次给每个位置选择当前位置及以后最小的元素（交换当前元素与之后最小元素的位置）。</p>
<p>不稳定举例：<br>排序前：5, 5*, 1, 7<br>排序后：1, 5*, 5, 7</p>
<p>时间复杂度$n^2$，空间复杂度1</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // selectSort 选择排序
        int minIndex;
        int n = nums.size();
        for (int i = 0; i &lt; n - 1; ++i) {
            minIndex = i;
            for (int j = i + 1; j &lt; n; ++j) {
                if (nums[j] &lt; nums[minIndex]) {
                    minIndex = j;
                }
            }
            swap(nums[i], nums[minIndex]);
        }
        return nums;
    }
};
</code></pre>
<h2 id="插入排序（Insect-Sort）（稳定排序）（超出时间限制）"><a href="#插入排序（Insect-Sort）（稳定排序）（超出时间限制）" class="headerlink" title="插入排序（Insect Sort）（稳定排序）（超出时间限制）"></a>插入排序（Insect Sort）（稳定排序）（超出时间限制）</h2><p>在前 1~i - 1元素有序的情况下，（依次）将第 i 个元素插入前面已经有序的小序列，使其有序。使用哨兵减少比较</p>
<p>时间复杂度$n^2$，空间复杂度1</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        int i, j;
        for (i = 2; i &lt;= nums.size(); i++) {
            if (nums[i] &lt; nums[i - 1]) {
                nums[0] = nums[i]; //nums[0]为哨兵
                for (j = i - 1; nums[0] &lt; nums[j]; j--) {
                    nums[j + 1] =nums[j];
                }
                nums[j + 1] = nums[0];
            }
        }
        return nums;
    }
};
</code></pre>
<p>插入排序在此基础上也可以将搜索和移动分开，使用二分查找先找到要插入位置，然后再移动</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        int i, j, low, high, mid;
        for (i = 2; i &lt;= nums.size(); i++) {
            nums[0] = nums[i];
            low = 1; high = i - 1;
            while (low &lt;= high) {
                mid = (low + high) / 2;
                if (nums[mid] &gt; nums[0]) high = mid - 1;
                else low = mid + 1;
            }
            for (j = i - 1; j &gt; high + 1; j--)
                nums[j + 1] = nums[j];
            nums[high + 1] = nums[0];
        }
        return nums;
    }
};
</code></pre>
<h2 id="希尔排序（Shell-Sort）（非稳定排序）"><a href="#希尔排序（Shell-Sort）（非稳定排序）" class="headerlink" title="希尔排序（Shell Sort）（非稳定排序）"></a>希尔排序（Shell Sort）（非稳定排序）</h2><p>改进的插入排序（优化：原数组的一个元素距离正确位置很远的情况）<br>先让间隔 h 的元素有序，在使得间隔为 h / 2，一直缩小，一直到 h = 1（此时数组有序）。</p>
<p>时间复杂度介于nlogn和$n^2$之间，空间复杂度1</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
    void shellSort(vector&lt;int&gt;&amp;nums, int gap, int i) {
        int j, tmp = nums[i];
        for (j = i - gap; j &gt;= 0 &amp;&amp; tmp &lt; nums[j]; j -= gap) {
            // 依次后移
            nums[j + gap] = nums[j];
        }
        nums[j + gap] = tmp;
    }
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        int n = nums.size();
        // 分组，最开始时，间隔 gap 为数组的一半
        for (int gap = n / 2; gap &gt;= 1 ; gap /= 2) {
            // 对各个分组进行插入分组
            for (int i = gap; i &lt; n; ++i) {
                shellSort(nums, gap, i);
            }
        }
        return nums;
    }
};
</code></pre>
<h2 id="归并排序（Merge-Sort）（稳定排序）"><a href="#归并排序（Merge-Sort）（稳定排序）" class="headerlink" title="归并排序（Merge Sort）（稳定排序）"></a>归并排序（Merge Sort）（稳定排序）</h2><p>将无序数组拆分，排序后再合并成大的有序数组。</p>
<p>时间复杂度nlogn，空间复杂度n</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
    vector&lt;int&gt; tmp;
    void merge (vector&lt;int&gt;&amp; nums, int low, int mid, int high) {
        for (int k = low; k &lt;= high; k++) {
            tmp[k] = nums[k];
        }

        int i, j;
        for (i = low, j = mid + 1, k = i; i &lt;= mid &amp;&amp; j &lt;=high; k++) {
            if (tmp[i] &lt;= tmp[j]) {
                nums[k] = tmp[i++];
            } else {
                nums[k] = tmp[j++];
            }
        }
        while (i &lt;= mid) nums[k++] = tmp[i++];
        while (j &lt;= high) nums[k++] = tmp[j++];
    }
public:
    vector&lt;int&gt; mergeSort(vector&lt;int&gt;&amp; nums, int low, int high) {
        if (low &lt; high) {
            int mid = (low + high) / 2;
            mergeSort(nums, low, mid + 1);
            mergeSort(nums, mid + 1, high);
            merge(nums, low, mid, high);
        }
    }
};
</code></pre>
<h2 id="快速排序（Quick-Sort）（非稳定排序）"><a href="#快速排序（Quick-Sort）（非稳定排序）" class="headerlink" title="快速排序（Quick Sort）（非稳定排序）"></a>快速排序（Quick Sort）（非稳定排序）</h2><p>随机选取一个数（x = rand() % len + startIndex）作为基准；<br>把比基准小的数交换到前面，比基准大的数交换到后面；<br>对左右区间递归重复。</p>
<p>时间复杂度nlogn，空间复杂度logn</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
    void quickSort(vector&lt;int&gt;&amp;nums, int startIndex, int endIndex) {
        if (startIndex &gt;= endIndex) return;
        
        int x = rand() % (endIndex - startIndex + 1) + startIndex; // 基于随机的原则
        swap(nums[startIndex], nums[x]);
        int firstNum = nums[startIndex];
        
        int l = startIndex, r = endIndex;
        while (l &lt; r) {
            // 从后往前走，将比第一个小的移到前面
            while (l &lt; r &amp;&amp; nums[r] &gt;= firstNum) --r;
            if (l &lt; r) {
                nums[l] = nums[r];
            }
            // 从前往后走，将比第一个大的移到后面
            while (l &lt; r &amp;&amp; nums[l] &lt;= firstNum) ++l;
            if (l &lt; r) {
                nums[r] = nums[l];
            }
        }
        nums[l] = firstNum;
        // 自顶向下
        quickSort(nums, startIndex, l - 1);
        quickSort(nums, l + 1, endIndex);
    }

public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        int n = nums.size();
        quickSort(nums, 0, n - 1);
        return nums;
    }
};
</code></pre>
<h2 id="堆排序（Heap-Sort）（非稳定排序）"><a href="#堆排序（Heap-Sort）（非稳定排序）" class="headerlink" title="堆排序（Heap Sort）（非稳定排序）"></a>堆排序（Heap Sort）（非稳定排序）</h2><p>先在原先数组的基础上构造大根堆（时间复杂度nlogn）；<br>再依次弹出最大元素（每次弹出的时间复杂度为logk，k为当前大根堆中元素数目）。</p>
<p>时间复杂度nlogn，空间复杂度1</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
    void buildMaxHeap(vector&lt;int&gt;&amp; nums) {
        int n = nums.size();
        for (int i = (n - 1) / 2; i &gt;= 0; --i) {
            maxHeapify(nums, i, n);
        }
    }

    void maxHeapify(vector&lt;int&gt;&amp; nums, int i, int n) {
        while (i * 2 + 1 &lt; n) {
            // 代表当前 i 节点的左右儿子；
            // 超出数组大小则代表当前 i 节点为叶子节点，不需要移位
            int lSon = 2 * i + 1;
            int rSon = 2 * i + 2;
            int large = i;
            if (lSon &lt; n &amp;&amp; nums[lSon] &gt; nums[i]) large = lSon;
            if (rSon &lt; n &amp;&amp; nums[rSon] &gt; nums[large]) large = rSon;

            if (large != i) {
                swap(nums[i], nums[large]);
                // 迭代判断对应子节点及其儿子节点的大小关系
                i = large;
            } else {
                break;
            }
        }
    }

public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // heapSort 堆排序
        int n = nums.size();
        // 将数组整理成大根堆
        buildMaxHeap(nums);
        for (int i = n - 1; i &gt;= 1; --i) {
            // 依次弹出最大元素，放到数组最后，当前排序对应数组大小 - 1
            swap(nums[0], nums[i]);
            --n;
            maxHeapify(nums, 0, n);
        }
        return nums;
    }
};
</code></pre>
<h2 id="计数排序（Count-Sort）（稳定排序）"><a href="#计数排序（Count-Sort）（稳定排序）" class="headerlink" title="计数排序（Count Sort）（稳定排序）"></a>计数排序（Count Sort）（稳定排序）</h2><p>创建数组 counts，用于统计原数组 nums 中各元素值的出现次数；<br>再依次将元素值赋值到 nums 中对应位置。</p>
<p>计数排序，时间复杂度n + k，空间复杂度k（k = maxNum - minNum + 1）</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // CountSort 计数排序
        int n = nums.size();
        int minNum = INT_MAX, maxNum = INT_MIN;
        // 找到数组中的最小和最大元素
        for (int i = 0; i &lt; n; ++i) {
            if (nums[i] &lt; minNum) minNum = nums[i];
            if (nums[i] &gt; maxNum) maxNum = nums[i];
        }
        // 构造计数数组
        vector&lt;int&gt; counts(maxNum - minNum + 1, 0);
        for (int i = 0; i &lt; n; ++i) {
            ++counts[nums[i] - minNum];
        }
        // 计数排序
        int index = 0;
        for (int i = 0; i &lt; counts.size(); ++i) {
            while (counts[i] != 0) {
                nums[index++] = i + minNum;
                counts[i]--;
            }
        }
        return nums;
    }
};
</code></pre>
<h2 id="桶排序（Bucket-Sort）（稳定排序）"><a href="#桶排序（Bucket-Sort）（稳定排序）" class="headerlink" title="桶排序（Bucket Sort）（稳定排序）"></a>桶排序（Bucket Sort）（稳定排序）</h2><p>将原数组的元素分到有限数量的桶里（大编号桶里的所有元素均大于小编号桶里的任意元素）；<br>分别对每个桶进行排序；<br>依次合并。</p>
<p>时间复杂度n + k，空间复杂度n + k（k为桶的数量）</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // BucketSort 桶排序
        int n = nums.size();
        // 获取数组的最小值和最大值
        int maxNum = nums[0], minNum = nums[0];
        for (int i = 1; i &lt; n; ++i) {
            if (nums[i] &gt; maxNum) maxNum = nums[i];
            if (nums[i] &lt; minNum) minNum = nums[i];
        }
        // 初始化桶
        int bucketNum = 5, bucketSize = (maxNum - minNum) / bucketNum + 1;
        vector&lt;vector&lt;int&gt;&gt; buckets(bucketNum, vector&lt;int&gt;(0));
        // 小至大分桶
        for (int num : nums) {
            int bucketIndex = (num - minNum) / bucketSize;
            buckets[bucketIndex].emplace_back(num);
        }
        // 桶内排序
        for (int i = 0; i &lt; buckets.size(); ++i) {
            sort(buckets[i].begin(), buckets[i].end());
        }
        // 从桶中依次取数
        int index = 0;
        for (auto&amp; bucket : buckets) {
            for (int num : bucket) {
                nums[index++] = num;
            }
        }

        return nums;
    }
};
</code></pre>
<h2 id="基数排序（Radix-Sort）（稳定排序）"><a href="#基数排序（Radix-Sort）（稳定排序）" class="headerlink" title="基数排序（Radix Sort）（稳定排序）"></a>基数排序（Radix Sort）（稳定排序）</h2><p>对数组中所有数依次按由低到高的位数进行多次排序；<br>每次排序都基于上次排序的结果。<br>（相对位置顺序保持不变）</p>
<p>例：原始数组 1，23，21，11，32<br>第一次排序后 1，21，11，32，23<br>第二次排序后 1，11，21，23，32<br>时间复杂度n x k，空间复杂度k（k为最大元素的位数）</p>
<p>代码：</p>
<pre><code class="cpp">class Solution {
    vector&lt;int&gt; counts;
    void radixSort(vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; tmp, int divisor) {
        int n = nums.size();
        counts = vector&lt;int&gt;(10, 0);
        // 统计个、十、百、千、万上对应 0 ~ 9 的出现次数
        for (int i = 0; i &lt; n; ++i) {
            int x = (nums[i] / divisor) % 10;
            ++counts[x];
        }
        // 前缀和
        for (int i = 1; i &lt;= 9; ++i) {
            counts[i] += counts[i - 1];
        }
        // 从后向前赋值
        for (int i = n - 1; i &gt;= 0; --i) {
            int x = (nums[i] / divisor) % 10;
            int index = counts[x] - 1;
            tmp[index] = nums[i];
            --counts[x];
        }
    }

public:
    vector&lt;int&gt; sortArray(vector&lt;int&gt;&amp; nums) {
        // RadixSort 基数排序
        int n = nums.size();
        // 预处理，让所有的数都大于等于0
        for (int i = 0; i &lt; n; ++i) {
            nums[i] += 50000; // 50000为最小可能的数组大小
        }
        // 找出最大的数字，并获得其最大位数
        int maxNum = nums[0];
        for (int i = 0; i &lt; n; ++i) {
            if (nums[i] &gt; maxNum) {
                maxNum = nums[i];
            }
        }
        int num = maxNum, maxLen = 0;
        while (num) {
            ++maxLen;
            num /= 10;
        }
        // 基数排序，低位优先
        int divisor = 1;
        vector&lt;int&gt; tmp(n, 0);
        for (int i = 0; i &lt; maxLen; ++i) {
            radixSort(nums, tmp, divisor);
            swap(tmp, nums);
            divisor *= 10;
        }
        // 减去预处理量
        for (int i = 0; i &lt; n; ++i) {
            nums[i] -= 50000;
        }
        return nums;
    }
};
</code></pre>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新：<time datetime="2024-01-04T02:41:48.350Z" itemprop="dateUpdated">2024-01-04 10:41:48</time>
</span>


        
        
        
    </div>
    <footer>
        <div onclick="location.href='https://nefelibata.icu'">
            <img src="/blog/img/avatar.jpg" alt="Nefelibata">
            <a>Nefelibata</a>
        </div>
    </footer>
</blockquote>

        
    <div class="page-reward">
        <nav class="myreward">
            <a id="rewardBtn" href="javascript:;"><span>打&nbsp;赏</span><span>装成好像很多人打赏的样子</span></a>
        </nav>
    </div>



        <div class="post-footer">
            

            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://nefelibata.icu/2022/10a444b428.html&title=《排序》 — Nefelibata&pic=https://nefelibata.icu/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://nefelibata.icu/2022/10a444b428.html&title=《排序》 — Nefelibata&source=排序" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://nefelibata.icu/2022/10a444b428.html" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《排序》 — Nefelibata&url=https://nefelibata.icu/2022/10a444b428.html&via=https://nefelibata.icu" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://nefelibata.icu/2022/10a444b428.html" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/blog/2022/12f1aaadb6.html" id="post-prev" class="post-nav-link">
        <h4 class="title" >
          上一篇：梦
        </h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/blog/2022/1072a96e3d.html" id="post-next" class="post-nav-link">
        <h4 class="title" data-hover="下一篇：中缀表达式转后缀表达式">下一篇：中缀表达式转后缀表达式</h4>
      </a>
    </div>
  
</nav>


</article>

</div>

        <footer class="footer">
    <div class="footer-content">
        <span class="power">
            <i class="icon icon-lg icon-copyright"></i>
            2021
            <i class="icon icon-lg icon-heart"></i>
            <a href="https://nefelibata.icu">nefelibata.icu</a>
        </span>
    </div>
</footer>

    </main>
    
        
<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        <span>感谢您的鼓励支持！</span>
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" data-img="/blog/img/dog.png" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/blog/img/wechat.png" data-alipay="/blog/img/alipay.png">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechatPay">&nbsp;&nbsp;微信&nbsp;&nbsp;</span>
                <span class="reward-toggle-item alipayPay">支付宝</span>
            </div>
        </label>
        
        <i class="icon icon-caret-up"></i>
    </div>
</div>


    
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://nefelibata.icu/2022/10a444b428.html&title=《排序》 — Nefelibata&pic=https://nefelibata.icu/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://nefelibata.icu/2022/10a444b428.html&title=《排序》 — Nefelibata&source=排序" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://nefelibata.icu/2022/10a444b428.html" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《排序》 — Nefelibata&url=https://nefelibata.icu/2022/10a444b428.html&via=https://nefelibata.icu" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://nefelibata.icu/2022/10a444b428.html" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p class="wechatshare">扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <!-- waves按钮特效 -->
<script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>

<!-- 主题配置脚本 -->
<script>
var BLOG = { ROOT: '/blog/', SHARE: true, REWARD: true };
</script>

<!-- jquery -->
<script src="/blog/js/jquery.min.js?v=3.0"></script>

<!-- 搜索 -->

<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item waves-block waves-effect" onclick="location.href='{path}'">
    <div class="title ellipsis" title="{title}">{title}</div>
</li>
</template>


<!-- main博客脚本 -->
<script src="/blog/js/main.min.js?v=3.0" ></script>

<!-- 动画&配置 -->
<script src="/blog/js/script.min.js?v=3.0" ></script>

<!-- 脚本管理 -->
<script>

if(window.innerWidth > 800){
	/* 3D标题 */
	$(".content-header").on("mousemove", threedee);

	/* 底部追随鼠标 */
	$(".footer").hover(2);

	/* gotop键的涟漪 */
	$("#gotop").hover(1);

	/* 赞赏的粒子雨 */
	$("#reward").hover(3);

	/* 微信公众号的底部渲染 */
	$("#wechat").hover(4);

    /* 标题跳动 */
    $(".archivestitle").bumpyText();

	/* 图片点击放大 */
	const postimg = jQuery(".post-content img:not(.github-emoji)");
	postimg.on("click",function(){

		mask.classList.add("in");
		main.classList.add("Mask");
		menu.classList.add("Mask");
		var myimg = this.cloneNode(true);
		myimg.classList.add("imgShow");

		setTimeout(function(){
			jQuery(myimg).animate({
				opacity:"1"
			},1000);
		},0);

		document.body.appendChild(myimg);

		myimg.onclick=function(){
			document.body.removeChild(myimg);
			mask.classList.remove("in");
			main.classList.remove("Mask");
			menu.classList.remove("Mask");
		};

	});

}

/* 名字跳动 */
$("#name").bumpyText();


/* 网站运行时间 */
// setInterval(function () {
// 	setTime("2021/3/27");
// }, 1000);

/* 文章块的淡出 */
postshow();

/* 座右铭 */
// 
//    getHitokoto();
// 


/* 粘贴提示 */
G($(".post-content"), location.href, "Nefelibata");


/* 控制台 */
if (window.console && window.console.log) {
	setTimeout(function () {
		console.log("\n %c Nefelibata %c  © kpl0111  http://nefelibata.icu \n\n", "color:#FFFFFB;background:#1abc9c;padding:5px 0;border-radius:.5rem 0 0 .5rem;", "color:#FFFFFB;background:#080808;padding:5px 0;border-radius:0 .5rem .5rem 0;");
	}, 0);
}

</script>




<!-- 公式渲染 -->

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
    }
});
</script>

<script async src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML" async></script>



<!-- 不蒜子 -->
<!--  -->

</body>
</html>
